package database;

import java.util.Enumeration;
import java.util.Hashtable;


import dbmanager.DBManager;

public class RecordDelete {
	
	private String table = "property_details";
	DBManager database;
	
	private Hashtable<Object, Object> oldHash;
	private String query = null;
	private String deleteCondition = "";
	
	public void setDatabase(DBManager database)
    {	
    	this.database = database;	
    }
    
	
	public void setTableName(String tableName) 
    {	
    	this.table = tableName;	
    }
    
		  
    /**
     * setDeleteHash() method will sets the condition for the table query part.
     * */
	 public void setDeleteHash(Hashtable<Object, Object> deleteHash) 
    {	
    	this.oldHash = new Hashtable<Object, Object>();
    	this.oldHash = deleteHash; 
    	deleteHashQuery(); // Calls the method for converting into the String.
    }
	    
	
    /**
     * deleteHashQuery() - It will creats the string from the Hash Table. Which get stores into the respected string variable.  
     * */
	private void deleteHashQuery() 
    {
		
		
    	if(table.length() != 0)
    	{
    		if(oldHash.isEmpty())
    		{
    			System.out.println(" Condition Value Is Not Present ");
				//query = "DELETE FROM " + table;
    		}
    		else
    		{
    			Enumeration keys = oldHash.keys();
        		while(keys.hasMoreElements())
        		{
        			String key = keys.nextElement().toString();
      			  	String value = oldHash.get(key).toString();
      			  	
      			    deleteCondition = deleteCondition + key + " = '" + value + "' AND ";
        		}
        		deleteCondition = deleteCondition.substring(0, deleteCondition.length() - 4);
    		}    		
    	}
    	else
		{
			System.out.println(" Table Name Does Not Exists. ");
		}
	}
	  
	public synchronized int getDelete()
    {
		
		
    	try
    	{    		
			query = "DELETE FROM " + table;
			
			try 
	  		{
				if(deleteCondition.length() != 0)
					query = query + " WHERE " + deleteCondition;
	  		} 
	  		catch (Exception e) { }
    		        		
    		System.out.println("The query is : " + query);
    		int j=database.getDelete(query);
    		if(j>0)
    		{
    			 System.out.println("Data deleted successfully");
    		}
    		return j;
    	}
	  	catch(Exception e)
	  	{
	  		  e.printStackTrace();
	  	}  	return 0;	 
    }
	public static void main(String[] args) 
	{
		
		
		DBManager db = new DBManager();
		db.getConnect();
		
		Hashtable<Object, Object> newHash = new Hashtable<Object, Object>();
		newHash.put("mid", "9377");
		newHash.put("pid", "9");
		//newHash.put("vt", "knowledge");
		newHash.put("pv", "9322");
		
		RecordDelete rd = new RecordDelete(); 
		rd.setDatabase(db);
		rd.setDeleteHash(newHash);
		rd.getDelete();
		db.closeConnection();
		}
}
